from . import api, request, logging, get_user_info
from ihome.models import House, Facility, Area
#!/usr/bin/env python
#._*_.conding:utf-8._*_
from ihome.constants import QINIU_DOMIN_PREFIX
from ihome.constants import HOME_PAGE_DATA_REDIS_EXPIRES
from . import api, request, logging
from ihome.models import House, Facility, Area, HouseImage
from ihome import constants, db
from flask import current_app, jsonify, g, session
from ihome.utils.response_code import RET
from ihome import redis_store
import datetime
from ihome.models import Order
from ihome.utils.pic_store import pic_store
from ihome.utils.common import get_user_info


@api.route("/houses/index")
def house_index():
    """房屋首页推荐后端接口"""

    try:
        houses_dict = redis_store.get("home_house")
        if houses_dict:
            return jsonify(errno=RET.OK, errmsg="OK", data=eval(houses_dict))
    except Exception as e:
        current_app.logger.error(e)

    try:
        houses = House.query.order_by(House.order_count.desc()).limit(constants.HOME_PAGE_MAX_HOUSES).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据异常")

    houses_dict = []
    for house in houses if houses else []:
        houses_dict.append(house.to_basic_dict())
    # 当对象列表字典有值才缓存进redis数据库
    if houses_dict:
        try:
            redis_store.setex("home_house",constants.HOME_PAGE_DATA_REDIS_EXPIRES, houses_dict)
        except Exception as e:
            current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg="OK", data=houses_dict)


@api.route("/houses")
def get_houses():
    """房屋数据搜索后端接口"""

    p = request.args.get("p", 1)
    sort_key = request.args.get("sk", "new")
    start_data_str = request.args.get("sd")  # 开始日期
    end_data_str = request.args.get("ed")   # 结束日期
    aid = request.args.get("aid", "")   # 区域id

    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 判断参数
    try:
        start_data = None
        end_data = None
        if start_data_str:
            start_data = datetime.datetime.strptime(start_data_str, "%Y-%m-%d")
        if end_data_str:
            end_data = datetime.datetime.strptime(end_data_str, "%Y-%m-%d")
        # 开始时间要小于结束时间
        if start_data and end_data:
            assert start_data <= end_data, Exception("开始时间大于结束时间")   # assert:断言
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    filters_s = []

    # 如果区域id存在
    if aid:
        filters_s.append(House.area_id == aid)

    # 过滤查询条件
    conflict_orders = None
    if start_data and end_data:                 # 订单入住时间 < 搜索离开时间， 订单离开时间 > 搜索入住时间
        conflict_orders = Order.query.filter(Order.begin_date < end_data, Order.end_date > start_data).all()
    elif start_data:
        conflict_orders = Order.query.filter(Order.end_date > start_data).all()
    elif end_data:
        conflict_orders = Order.query.filter(Order.begin_date < end_data).all()

    if conflict_orders:
        # 如果冲突订单里面有值，取到冲突订单的房屋id
        conflict_house_ids = [order.house_id for order in conflict_orders]
        filters_s.append(House.id.notin_(conflict_house_ids))

    filters = []    # 订单排序过滤列表
    if sort_key == "booking":   # 订单量从高到低
        filters.append(House.order_count.desc())
    elif sort_key == "price-inc":   # 价格从低到高
        filters.append(House.price.asc())
    elif sort_key == "price-des":
        filters.append(House.price.desc())
    else:
        filters.append(House.create_time.desc())

    # 查询各过滤条件
    try:
        house_query = House.query.filter(*filters_s).order_by(*filters)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据异常")

    # 进行分页查询
    try:
        paginate = house_query.paginate(p, constants.HOUSE_LIST_PAGE_CAPACITY, False)
        houses = paginate.items
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询房屋对象异常")

    houses_dict = []
    for house in houses if houses else []:
        houses_dict.append(house.to_basic_dict())

    return jsonify(errno=RET.OK, errmsg="OK", data={"houses": houses_dict,
                                                    "total_page": total_page})



"""城区信息数据查询"""
@api.route('/areas')
def get_areas_info():
    #查询城区信息

    #先从缓存中去取，如果缓存中没有，再去数据库中取
    try:
        areas = redis_store.get('area_info')
    except Exception as e:
        logging.error(e)
        areas = None

    #如果不为空，做查询操作
    if areas:
        return jsonify(errno=RET.OK, errmsg='获取成功', data=eval(areas))

    try:
        areas = Area.query.all()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取城区信息失败')

    areas_list = []
    for area in areas:
        areas_list.append(area.to_dict())

    #存储json_areas数据到redis缓存中
    try:
        redis_store.setex('area_info', constants.AREA_INFO_REDIS_EXPIRES, areas_list)
    except Exception as e:
        logging.error(e)

    return jsonify(errno=RET.OK, errmsg='获取成功', data=areas_list)


"""新房源发布"""
@api.route('/houses', methods=['POST'])
@get_user_info
def save_new_house():
    #获取用户id
    user_id = g.user

    #获取数据
    json_dict = request.get_json()
    if not json_dict:
        return jsonify(errno=RET.PARAMERR, errmsg='请输入参数')

    title = json_dict.get('title')
    price = json_dict.get('price')
    address = json_dict.get('address')
    area_id = json_dict.get('area_id')
    room_count = json_dict.get('room_count')
    acreage = json_dict.get('acreage')
    unit = json_dict.get('unit')
    capacity = json_dict.get('capacity')
    beds = json_dict.get('beds')
    deposit = json_dict.get('deposit')
    min_days = json_dict.get('min_days')
    max_days = json_dict.get('max_days')

    if not all(
            [title, price, address, area_id, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')

    try:
        price = int(float(price) * 100)
        deposit = int(float(deposit) * 100)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 设置数据到模型user_id
    house = House()
    house.user_id = user_id.id
    house.area_id = area_id
    house.title = title
    house.price = price
    house.address = address
    house.room_count = room_count
    house.acreage = acreage
    house.unit = unit
    house.capacity = capacity
    house.beds = beds
    house.deposit = deposit
    house.min_days = min_days
    house.max_days = max_days

    # 设置设施信息
    facility = json_dict.get('facility')
    if facility:
        facilities = Facility.query.filter(Facility.id.in_(facility)).all()
        house.facilities = facilities

    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存房屋信息失败')

    return jsonify(errno=RET.OK, errmsg='OK', data={'house_id': house.id})


"""上传房源图片"""
@api.route('/houses/<int:house_id>/images',methods=["POST"])
@get_user_info
def upload_house_pic(house_id):

    house_pic = request.files.get("house_image")

    # 取到图片文件
    try:
        house_image_file = house_pic.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足')
    if not house_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    # 尝试查询房屋数据
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询房屋数据失败')

    if not house:
        return jsonify(errno=RET.NODATA, errmsg='房屋不存在')

    # 使用七牛上传图片
    url = None
    try:
        url = pic_store(house_image_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片到七牛失败")
    if not url:
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云上传图片异常")

    # 生成房屋图片模型并保存至数据数据库
    house_image = HouseImage()
    house_image.house_id = house_id
    house_image.url = url

    # 判断房屋是否有主图片，如果没有，则设置
    if not house.index_image_url:
        house.index_image_url = url

    # 更新到数据库
    try:
        db.session.add(house_image)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存房屋图片失败")

    # 返回数据
    return jsonify(errno=RET.OK, errmsg='OK', data={'url': QINIU_DOMIN_PREFIX + url})


"""获取房屋详情信息"""
@api.route("/houses/<int:house_id>")
def get_house_detail(house_id):
    print("--------------获取房屋详情信息---------------")
    #先从redis中去取数据
    # 获取到当前登录用户的id，如果没有登录，那么就返回-1
    user_id = session.get("user_id", -1)

    # try:
    #     house_dict = redis_store.get("house_detail_%d" % house_id)
    #     if house_dict:
    #         return jsonify(errno=RET.NODATA, errmsg='OK',data={"user_id":user_id,"house":eval(house_dict)})
    # except Exception as e:
    #     current_app.logger.error(e)


    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not house:
        return jsonify(errno=RET.NODATA, errmsg="房屋不存在")

    house_dict = house.to_full_dict()

    #缓存当前房屋数据
    # try:
    #     redis_store.set(("house_detail_%d" % house_id), house_dict, HOME_PAGE_DATA_REDIS_EXPIRES)
    # except Exception as e:
    #     current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='OK',data={"user_id": user_id,
                                                       "house": house_dict})



